package com.shujia;

import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

// 创建连接池，后续调用MySQL连接可以直接从池中获取，调用完以后，再将连接放至连接池中
public class ConnectPool {

    private static List<Connection> connPool = new LinkedList<Connection>();

    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileReader("source/jdbc.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Class.forName(properties.getProperty("driver"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try {
            for (int i = 0; i < 10; i++) {
                Connection connection = DriverManager.getConnection(
                        properties.getProperty("url"),
                        properties.getProperty("user"),
                        properties.getProperty("password")
                );
                // 将创建好的连接放至连接池中
                connPool.add(connection);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static synchronized Connection getConn(){

        if (connPool.size() == 0){
            try {
                // 如果当前连接池中没有连接可以获取，那么通过class.wait方法可以将线程进行暂定等待
                ConnectPool.class.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return connPool.remove(0);
    }

    public static synchronized void setConn(Connection connection){

        connPool.add(connection);
        // 如果当前连接池中有连接了，可以唤醒一个等待的线程
        ConnectPool.class.notify();
    }

}
